<!--
 *  
 * @Author: QUAN
 *  
-->
<template>
  <div class="badge-detail">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'BadgeList' }">
        徽章管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        {{ editMode ? '徽章详情' : '新增徽章' }}
      </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容 -->
    <el-form
      :model="info"
      label-width="130px"
      :rules="badgeRule"
      label-position="right"
      ref="badgeForm"
    >
      <el-form-item prop="id" label="徽章ID：">
        <span>{{ info.id }}</span>
      </el-form-item>
      <el-form-item prop="title" label="徽章品类：">
        <el-input v-model="info.title" placeholder="请输入徽章品类"></el-input>
      </el-form-item>
      <el-form-item prop="scheme" label="跳转链接：">
        <el-input
          v-model="info.scheme"
          placeholder='"去获得徽章"按钮跳转链接（需填写scheme码链接）'
        ></el-input>
      </el-form-item>
      <el-form-item prop="levels" label="徽章等级：">
        <div class="badge-box">
          <p class="explain">（需要不可升级的徽章时，只添加一个等级即可）</p>
          <div class="badge-item" v-for="(item, index) in info.levels" :key="index">
            <p class="header">
              <span>等级{{ index + 1 }}</span>
              <el-button type="danger" @click="delLevels(item, index)">删除</el-button>
            </p>
            <el-form-item
              label="徽章等级名称:"
              :prop="`levels.${index}.title`"
              :rules="validateBase"
            >
              <el-input v-model="item.title" placeholder="请输入徽章等级名称"></el-input>
            </el-form-item>
            <el-form-item label="已获得状态icon:">
              <upload-resource
                is-public
                @upload="(img) => $set(item, 'activeIcon', img.url)"
                :folder="'actImg' + '/' + imgDate"
              ></upload-resource>
              <img class="icon-img" :src="item.activeIcon" alt="" />
            </el-form-item>
            <el-form-item label="未获得状态icon:">
              <upload-resource
                is-public
                @upload="(img) => $set(item, 'inactiveIcon', img.url)"
                :folder="'actImg' + '/' + imgDate"
              ></upload-resource>
              <img class="icon-img" :src="item.inactiveIcon" alt="" />
            </el-form-item>
            <el-form-item
              label="获得条件:"
              :prop="`levels.${index}.ruleCode`"
              :rules="validateBase"
            >
              <div class="rule-box">
                <el-select v-model="item.ruleCode" placeholder="请选择">
                  <el-option
                    v-for="(it, ind) in badgeLevRule"
                    :key="ind"
                    :label="it.label"
                    :value="it.value"
                  ></el-option>
                </el-select>
                <el-input v-model="item.ruleMetric" placeholder="请填写数值"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="是否生效:">
              <el-radio-group v-model="item.enable">
                <el-radio :label="1">生效</el-radio>
                <el-radio :label="0">不生效</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="id" label="徽章状态：">
        <span>{{ info.online ? '上线' : '下线' }}</span>
      </el-form-item>
      <el-row class="to-center">
        <el-button type="primary" size="medium" :loading="saveLoading" @click="save">
          保存
        </el-button>
        <el-button type="success" size="medium" @click="showDialog">添加新等级</el-button>
      </el-row>
    </el-form>

    <!-- dialog -->
    <el-dialog
      :visible="dialogVisible"
      title="新增徽章等级"
      center
      width="60%"
      @close="dialogVisible = false"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <el-form
        :model="dialogForm"
        label-width="160px"
        :rules="badgeDialogRule"
        label-position="right"
        ref="badgeDialogForm"
      >
        <el-form-item prop="title" label="徽章等级名称:">
          <el-input placeholder="请输入徽章等级名称" v-model="dialogForm.title"></el-input>
        </el-form-item>
        <el-form-item prop="activeIcon" label="徽章已获得状态icon:">
          <upload-resource
            is-public
            @upload="(img) => $set(dialogForm, 'activeIcon', img.url)"
            :folder="'actImg' + '/' + imgDate"
          ></upload-resource>
          <img class="icon-img" :src="dialogForm.activeIcon" alt="" />
        </el-form-item>
        <el-form-item prop="inactiveIcon" label="徽章未获得状态icon:">
          <upload-resource
            is-public
            @upload="(img) => $set(dialogForm, 'inactiveIcon', img.url)"
            :folder="'actImg' + '/' + imgDate"
          ></upload-resource>
          <img class="icon-img" :src="dialogForm.inactiveIcon" alt="" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGrade">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import EditMixins from 'mixins/Edit';
  import { FormRuleConf } from '@/config';
  import UploadResource from 'comp/UploadResource';
  export default {
    mixins: [EditMixins],
    components: {
      UploadResource,
    },
    data() {
      return {
        validateBase: [
          { type: 'string', required: true, trigger: 'blur', message: '该项为必填项' },
        ], // 属性必填项的验证
        ...FormRuleConf.Badge, // 验证规则
        dialogVisible: false, //dialog
        dialogForm: {}, //dialog表单
        saveLoading: false, //表单loading
        badgeLevRule: [], //徽章等级规则
      };
    },
    computed: {
      // 生成时间文件夹
      imgDate: function() {
        return this.dayjs().format('YYYY-MM-DD');
      },
    },
    created() {},
    mounted() {
      // 获取徽章等级规则
      this.getBadgeRule();
    },
    methods: {
      // 获取徽章等级规则
      getBadgeRule() {
        this.$service.BadgeLevelRule().then((res) => {
          Object.keys(res).forEach((item) => {
            let _ = {};
            _.label = res[item];
            _.value = item;
            this.badgeLevRule.push(_);
          });
        });
      },

      // 增加等级
      addGrade() {
        this.$refs.badgeDialogForm.validate((valid) => {
          if (valid) {
            if (!this.info.levels || !this.info.levels.length) {
              this.$set(this.info, 'levels', []);
            }
            this.info.levels.push(this.dialogForm);
            this.dialogVisible = false;
            this.dialogForm = {};
          }
        });
      },

      // 删除等级
      delLevels(val, i) {
        this.$confirm('确定删除该等级吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            if (this.editMode) {
              this.$service.BadgeLevelDelete({ id: val.id }).then((res) => {
                this.$message.success('删除成功');
                this.$tabs.open({
                  name: 'BadgeDetail',
                  params: { id: this.info.id },
                });
              });
            } else {
              // 如果是新增就直接本地操作
              this.info.levels.splice(i, 1);
            }
          })
          .catch(() => {});
      },

      // 展示增加等级的dailog
      showDialog() {
        this.dialogVisible = true;
      },

      // 保存
      save() {
        if (this.saveLoading) return;
        this.$refs.badgeForm.validate((valid) => {
          if (valid) {
            this.saveLoading = true;
            // 后端需要index和online
            this.info.levels && this.info.levels.map((item, index) => {
              item.level = index + 1;
              item.online = item.online || 0;
              return item;
            });
            this.$service.BadgeSave(this.info, JSON_HEADER).then((res) => {
              this.saveLoading = false;
              this.$message.success('保存成功');
              this.$tabs.open({
                name: 'BadgeDetail',
                params: { id: res },
              });
            });
          }
        });
      },

      // 得到数据
      getInfo() {
        if (!this.id || this.$route.name != 'BadgeDetail' || this.infoGetting) return;
        this.infoGetting = true;
        this.$service
          .BadgeDetail({ id: this.id })
          .then((res) => {
            this.info = { ...res };
          })
          .finally(() => {
            this.infoGetting = false;
          });
      },
    },
  };
</script>
<style lang="less" scoped>
  // element样式覆盖
  /deep/ .el-dialog {
    // 限制上传图片大小
    .icon-img {
      max-width: 80px;
      margin-top: 10px;
    }
  }

  .badge-detail {
    .badge-box {
      .explain {
        font-size: 12px;
        color: #e6a23c;
      }
      .badge-item {
        display: inline-block;
        padding: 20px;
        border: 1px solid #aaa;
        max-width: 390px;
        border-radius: 10px;
        margin-right: 20px;
        .header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
        }
        // 限制上传图片大小
        .icon-img {
          max-width: 80px;
          margin-top: 10px;
        }
      }
    }
    // 按钮居中
    .to-center {
      text-align: center;
    }
    .rule-box {
      display: flex;
      /deep/ .el-input {
        width: 130px;
      }
    }
  }
</style>
